package com.whpost.service.service.cwqf;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.whpost.service.dao.cwqf.TQfkbBkDao;
import com.whpost.service.dao.cwqf.VwCwqfMapper;
import com.whpost.service.entity.cwqf.*;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.BaseServices;
import com.whpost.service.tools.ToolBean;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

@Service
public class QfkbApiServices extends BaseServices<TQfkbBkDao,TQfkbBk> {

    @Resource
    private TQfkbBkDao tQfkbBkDao;
    @Resource
    private VwCwqfMapper vwCwqfMapper;

    /**
     * 机构看板数据；
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo jgkbInitData(String loginId,Map<String, Object> map) throws UnsupportedEncodingException {
        JSONObject data=getData(map,loginId);
        String rq=data.getString("rq");
        String jb=data.getString("jb");
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(401, "未登录！", null);
        }

        // 返回结果容器
        Map<String, Object> rtnMap = new HashMap<>();



        /* 2. 欠费汇总（市州级 jb=2） */
        if("2".equals(jb)) {
            List<Jb2FeeSummary> summaryList = vwCwqfMapper.getJb2QfSummary(rq);
            List<MergedJb2FeeSummary> mergedList = mergeFeeSummaries(summaryList);
            rtnMap.put("mergedJb2FeeSummaryList", mergedList);
        }else if("3".equals(jb)){
            String pcode=data.getString("pcode");
            List<Jb3FeeSummary> summaryList = vwCwqfMapper.getJb3QfSummary(rq,pcode);
            List<MergedJb3FeeSummary> mergedList = mergeFeeSummariesJb3(summaryList);
            rtnMap.put("mergedJb2FeeSummaryList", mergedList);
        }
        /* 3. 返回 */
        ResultInfo resultInfo = new ResultInfo(200, "成功返回！", rtnMap);
        return backRtn(resultInfo, loginId);
    }

    /**
     * 专业看板数据；
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo zykbInitData(String loginId,Map<String, Object> map) throws UnsupportedEncodingException {
        JSONObject data=getData(map,loginId);
        String rq=data.getString("rq");
        String jb=data.getString("jb");


        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(401, "未登录！", null);
        }
        List<Zyqf> zyqfList=new ArrayList<>();
        // 返回结果容器
        Map<String, Object> rtnMap = new HashMap<>();
        if(jb.equals("1")){
            zyqfList= vwCwqfMapper.getZyQfSummary(rq);
            // 先判断是否为 null，再判断是否为空集合（短路逻辑：若为 null 则不再执行 size()）
            if (zyqfList == null || zyqfList.size() == 0) {
                zyqfList = vwCwqfMapper.getZyQfSummaryIsNew();
            }
        }else if(jb.equals("2")) {
            String zy=data.getString("zy");
            zyqfList= vwCwqfMapper.getZyQfSummaryZy(rq,zy);
            // 先判断是否为 null，再判断是否为空集合（短路逻辑：若为 null 则不再执行 size()）
            if (zyqfList == null || zyqfList.size() == 0) {
                zyqfList = vwCwqfMapper.getZyQfSummaryZyIsNew(zy);
            }
        }else if(jb.equals("3")) {
            String zy=data.getString("zy");
            String pcode=data.getString("pcode");
            zyqfList= vwCwqfMapper.getZyQfSummaryZy2(rq,zy,pcode);
            // 先判断是否为 null，再判断是否为空集合（短路逻辑：若为 null 则不再执行 size()）
            if (zyqfList == null || zyqfList.size() == 0) {
                zyqfList = vwCwqfMapper.getZyQfSummaryZy2IsNew(zy,pcode);
            }
        }else if(jb.equals("4")) {
            String zy=data.getString("zy");
            String pcode=data.getString("pcode");
            zyqfList= vwCwqfMapper.getZyQfSummaryZy3(rq,zy,pcode);
            // 先判断是否为 null，再判断是否为空集合（短路逻辑：若为 null 则不再执行 size()）
            if (zyqfList == null || zyqfList.size() == 0) {
                zyqfList = vwCwqfMapper.getZyQfSummaryZy3IsNew(zy,pcode);
            }
        }
        rtnMap.put("zyqfList",zyqfList);

        /* 3. 返回 */
        ResultInfo resultInfo = new ResultInfo(200, "成功返回！", rtnMap);
        return backRtn(resultInfo, loginId);
    }

    public ResultInfo qskbInitData(String loginId,Map<String, Object> map) throws UnsupportedEncodingException {
        JSONObject data=getData(map,loginId);
        String rq=data.getString("rq");
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(401, "未登录！", null);
        }

        // 返回结果容器
        Map<String, Object> rtnMap = new HashMap<>();
        List<Qsyqqf> qsyqqfList = vwCwqfMapper.getQsyqqfSummary(rq);
        if (qsyqqfList == null || qsyqqfList.size() == 0) {
            qsyqqfList = vwCwqfMapper.getQsyqqfSummaryIsNew();
        }
        rtnMap.put("qsyqqfList",qsyqqfList);
        /* 3. 返回 */
        ResultInfo resultInfo = new ResultInfo(200, "成功返回！", rtnMap);
        return backRtn(resultInfo, loginId);
    }

    /**
     * 客户经理看板数据；
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo khjlkbInitData(String loginId,Map<String, Object> map) throws UnsupportedEncodingException {
        JSONObject data=getData(map,loginId);
        String rq=data.getString("rq");
        String khjl=data.getString("khjl");
        if (StringUtils.isEmpty(loginId)) {
            return new ResultInfo(401, "未登录！", null);
        }

        // 返回结果容器
        Map<String, Object> rtnMap = new HashMap<>();




        List<Jb2FeeSummary> summaryList = vwCwqfMapper.getJb2QfSummary(rq);
        List<MergedJb2FeeSummary> mergedList = mergeFeeSummaries(summaryList);
        rtnMap.put("mergedJb2FeeSummaryList", mergedList);
        /* 3. 返回 */
        ResultInfo resultInfo = new ResultInfo(200, "成功返回！", rtnMap);
        return backRtn(resultInfo, loginId);
    }



    /**
     * 欠费看板首页数据初始化:看板信息等等；
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo indexInit(String loginId) {

        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(401,"未登录！",null);
        }else{
            //定义返回的map
            Map<String,Object> rtnMap = new HashMap<>();
            //定义看板版块信息
            List<TQfkbBk> tQfkbBkList = new ArrayList<TQfkbBk>();
            tQfkbBkList = tQfkbBkDao.selectList(new QueryWrapper<TQfkbBk>().eq("state","1").eq("lx","0").orderByAsc("xh"));


            rtnMap.put("TqfkbBkList",tQfkbBkList);

            //日期
            String rq = ToolBean.getTodayStr("yyyy-MM-dd");
            rtnMap.put("rq",rq);

            List<Jb2FeeSummary> jb2FeeSummaryList = vwCwqfMapper.getJb2QfSummary(rq);
            List<MergedJb2FeeSummary> mergedJb2FeeSummaryList = mergeFeeSummaries(jb2FeeSummaryList);
            rtnMap.put("mergedJb2FeeSummaryList",mergedJb2FeeSummaryList);

            List<Zyqf> zyqfList = vwCwqfMapper.getZyQfSummary(rq);
            // 先判断是否为 null，再判断是否为空集合（短路逻辑：若为 null 则不再执行 size()）
            if (zyqfList == null || zyqfList.size() == 0) {
                zyqfList = vwCwqfMapper.getZyQfSummaryIsNew();
            }
            rtnMap.put("zyqfList",zyqfList);

            ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }

    }

    public List<MergedJb2FeeSummary> mergeFeeSummaries(List<Jb2FeeSummary> jb2FeeSummaryList) {
        // 预定义20个不重复的颜色代码
        String[] presetColors = {
                "#FF5733", "#33FF57", "#3357FF", "#F3FF33", "#FF33F3",
                "#33FFF3", "#F333FF", "#FF9933", "#99FF33", "#33FF99",
                "#3399FF", "#9933FF", "#FF3399", "#993333", "#339933",
                "#333399", "#999933", "#993399", "#339999", "#999999"
        };

        // 使用LinkedHashMap保持插入顺序，key为机构名称
        Map<String, MergedJb2FeeSummary> mergedMap = new LinkedHashMap<>();
        // 记录当前已使用的颜色索引
        int colorIndex = 0;

        for (Jb2FeeSummary summary : jb2FeeSummaryList) {
            String jb2Name = summary.getJb2Name();
            String jb2Code = summary.getJb2Code();

            // 获取或创建该机构的合并对象（首次出现时按顺序插入）
            MergedJb2FeeSummary merged = mergedMap.getOrDefault(jb2Name, new MergedJb2FeeSummary(jb2Name,jb2Code));

            // 首次处理该机构时创建对象并分配颜色
            if (merged != null) {
                // 按顺序分配颜色，超过预设数量后循环使用
                merged.setYsdm(presetColors[colorIndex % presetColors.length]);
                colorIndex++;
            }

            // 获取当前记录的欠费和逾期金额，避免null
            BigDecimal totalAmount = summary.getTotalAmount() != null ? summary.getTotalAmount() : BigDecimal.ZERO;
            BigDecimal overdueTotal = summary.getOverdueTotal() != null ? summary.getOverdueTotal() : BigDecimal.ZERO;

            // 根据数据来源(zyName)累加到相应字段
            if ("jd".equals(summary.getZyName())) {
                merged.setJdFee(totalAmount);
                merged.setJdOverdue(overdueTotal);
            } else if ("yw".equals(summary.getZyName())) {
                merged.setYwFee(totalAmount);
                merged.setYwOverdue(overdueTotal);
            }

            // 计算综合欠费和综合逾期（两者之和）
            merged.setTotalFee(merged.getTotalFee().add(totalAmount));
            merged.setTotalOverdue(merged.getTotalOverdue().add(overdueTotal));

            // 将合并对象放回Map
            mergedMap.put(jb2Name, merged);
        }

        // 将Map中的值转换为List，保持插入顺序
        return new ArrayList<>(mergedMap.values());
    }

    public List<MergedJb3FeeSummary> mergeFeeSummariesJb3(List<Jb3FeeSummary> jb3FeeSummaryList) {
        // 使用LinkedHashMap保持插入顺序，key为机构名称
        Map<String, MergedJb3FeeSummary> mergedMap = new LinkedHashMap<>();

        for (Jb3FeeSummary summary : jb3FeeSummaryList) {
            String jb3Name = summary.getJb3Name();
            String jb3Code = summary.getJb3Code();

            // 获取或创建该机构的合并对象（首次出现时按顺序插入）
            MergedJb3FeeSummary merged = mergedMap.getOrDefault(jb3Name, new MergedJb3FeeSummary(jb3Name,jb3Code));

            // 获取当前记录的欠费和逾期金额，避免null
            BigDecimal totalAmount = summary.getTotalAmount() != null ? summary.getTotalAmount() : BigDecimal.ZERO;
            BigDecimal overdueTotal = summary.getOverdueTotal() != null ? summary.getOverdueTotal() : BigDecimal.ZERO;

            // 根据数据来源(zyName)累加到相应字段
            if ("jd".equals(summary.getZyName())) {
                merged.setJdFee(totalAmount);
                merged.setJdOverdue(overdueTotal);
            } else if ("yw".equals(summary.getZyName())) {
                merged.setYwFee(totalAmount);
                merged.setYwOverdue(overdueTotal);
            }

            // 计算综合欠费和综合逾期（两者之和）
            merged.setTotalFee(merged.getTotalFee().add(totalAmount));
            merged.setTotalOverdue(merged.getTotalOverdue().add(overdueTotal));

            // 将合并对象放回Map（首次出现时会按顺序插入）
            mergedMap.put(jb3Name, merged);
        }

        // 将Map中的值转换为List，保持插入顺序
        return new ArrayList<>(mergedMap.values());
    }

    /**
     * 其它维护数据
     * @param loginId
     * @return
     * @throws UnsupportedEncodingException
     */
    public ResultInfo qtwhInit(String loginId) {

        if (StringUtils.isEmpty(loginId)){
            return new ResultInfo(401,"未登录！",null);
        }else{
            //定义返回的map
            Map<String,Object> rtnMap = new HashMap<>();
            //定义看板版块信息
            List<TQfkbBk> tQfkbBkList = new ArrayList<TQfkbBk>();
            tQfkbBkList = tQfkbBkDao.selectList(new QueryWrapper<TQfkbBk>().eq("state","1").eq("lx","1").orderByAsc("xh"));
            rtnMap.put("TqfkbBkList",tQfkbBkList);

            ResultInfo resultInfo = new ResultInfo(200, "成功返回！",rtnMap);
            return backRtn(resultInfo,loginId);
        }

    }

}
